# 导入蓝图类
from datetime import datetime

from flask import render_template, Blueprint, request, redirect, session, url_for
# 导入文章数据表模型
from model.article import Article
from ext import db
from sqlalchemy import desc

import json

# 创建蓝图实例
bp = Blueprint('index', __name__, url_prefix='/')


@bp.route('/')
def index():
    article = Article()
    # 根据id降序排列
    article_list = article.query.order_by(desc(Article.id)).all()

    data = {
        "title": "首页",
        "article_list": article_list
    }
    return render_template('index.html', data=data)


@bp.route('/article_add', methods=['GET', 'POST'])
def article_add():
    data = {
        "title": "发布文章"
    }

    if session.get('is_login') is None:
        return redirect(url_for('user.login'))

    if request.method == "POST":

        # 获取表单数据
        title = request.form['title']
        content = request.form['content']
        # 获取作者id(登录账号id)
        # login_user_info=json.loads(session.get('login_user_info'))
        author_id=session.get('login_user_id')
        article = Article(title=title, content=content,author_id=author_id)
        db.session.add(article)
        db.session.commit()
        # 自动跳转到文章列表: 一定要添加return关键词
        return redirect('/')
    else:
        return render_template('article_add.html', data=data)
    # return render_template('article_add.html', data=data)


@bp.route('/article_del/<int:article_id>',methods=['GET'])
def article_del(article_id):
    if id:
        # 先查询到待删除数据
        article = Article.query.get(article_id)
        # 将待删除数据添加到缓冲区
        db.session.delete(article)
        # 提交删除操作
        db.session.commit()
        return redirect('/')

@bp.route('/about')
def about():
    data = {
        "title": "关于我们"
    }
    return render_template('about.html', data=data)


@bp.route('/contact')
def contact():
    data = {
        "title": "联系我们"
    }
    return render_template('contact.html', data=data)


@bp.route('/news_detail')
def news_detail():
    id = request.args.get('id', '暂无数据')
    if id:
        # title = request.args.get('title', '暂无数据')
        # content = request.args.get('content', '暂无数据')
        # 根据文章id查询文章详情
        data=Article.query.get(id)
        return render_template('news_detail.html', data=data)
    else:
        return redirect('/')
